package com.dvj.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {

    /**
     * 使用JSON序列化机制，进行消息转换
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public Exchange stockEventExchange() {
        return ExchangeBuilder.topicExchange("stock-event-exchange").durable(true).build();
    }

    @Bean
    public Queue stockReleaseStockQueue() {
        return QueueBuilder.durable("stock.release.stock.queue").build();
    }

    @Bean
    public Queue stockDelayQueue() {
        /*
         * x-dead-letter-exchange: stock-event-exchange
         * x-dead-letter-routing-key: order.release.order
         * x-message-ttl: 60000
         */
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", "stock-event-exchange");
        args.put("x-dead-letter-routing-key", "stock.release");
        args.put("x-message-ttl", 120000);
        return QueueBuilder.durable("stock.delay.queue").withArguments(args).build();
    }

    @Bean
    public Binding stockReleaseBinding(@Qualifier("stockReleaseStockQueue") Queue queue,
                                       @Qualifier("stockEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue)
                .to(exchange)
                .with("stock.release.#")
                .noargs();
    }

    @Bean
    public Binding stockLockedBinding(@Qualifier("stockDelayQueue") Queue queue,
                                      @Qualifier("stockEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue)
                .to(exchange)
                .with("stock.locked")
                .noargs();
    }

}
